package com.whiteseason.spark.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object NetworkWordCount {

  def updateFunc (inputSum:Seq[Int], resultSum:Option[Int]): Option[Int] = {
    val finalResult: Int = inputSum.sum + resultSum.getOrElse(0)
    Option(finalResult)
  }

  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWorldCount")
    val ssc = new StreamingContext(conf,Seconds(2))

    //ssc.checkpoint("e:/tmp/sparkcheckpoint")
    val lines: ReceiverInputDStream[String] =  ssc.socketTextStream("spark",9999)

    val words = lines.flatMap( _.split(" "))

    val pairs = words.map(word => (word,1))
    //val pairs : DStream[(String,Int)] = words.map(word => (word,1))

    val wordCount = pairs.reduceByKey(_+_)
    //val wordCount = pairs.updateStateByKey(updateFunc)

    wordCount.print()

    ssc.start()

    ssc.awaitTermination()
  }
}
